
import React, { useState, useEffect, useContext } from 'react';
import { Toast, List, SwipeAction } from 'antd-mobile';
import { observer } from "mobx-react-lite";
import { useHistory } from "react-router-dom";
import moment from 'moment';

import ChatInboxCard from '../../../components/ChatInboxCard';
import { resolveMsgFormContent } from '../../../utils/index';
import { MySdkStoreContext } from '../../../context';
import { ConversationType } from '../../../constants';

import './style.scss';

const ConverList = observer(() => {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const [listByGroup, setListByGroup] = useState([]);
  const [topModeId, setTopModeId] = useState();
  const [collectionCompProps, setCollectCompProps] = useState({ visible: false });

  useEffect(() => {
    getConverByGroup();
  }, []);

  useEffect(() => {
    if(mySdkStore.newMessageData && mySdkStore.newMessageData.length) {
      getConverByGroup();
    }
  }, [mySdkStore.newMessageData]);

  const getConverByGroup = async() => {
    const groupList = (await mySdkStore.sdk.queryConversationGroups()??[]).map(item => ({...item, list: []}));
    const topModeId = groupList.find(item => item.groupName.indexOf('置顶') > -1)?.id;
    setTopModeId(topModeId);
    const promiseList = groupList.map(item => mySdkStore.sdk.queryConversationListByGroup({ groupId: item.id, pageIndex: 1, pageSize: 2 }));
    const data: any = await Promise.allSettled(promiseList);
    groupList.forEach((item, index) => {
      const { status, value: { list } } = data[index];
      if (status === 'fulfilled') {
        const newConvers = list.map(conver => {
          const { gmtCreate, lastMsgContentType, lastMsgContent, lastMsgSenderId, lastMsgRecallStatus } = conver;
          const lastMsg = lastMsgRecallStatus > 0 ? `${lastMsgSenderId === mySdkStore.mockConfig.userId ? '你' : '对方'}撤回了一条消息`: resolveMsgFormContent(lastMsgContentType, lastMsgContent);
          return { ...conver, gmtCreate: moment(gmtCreate).format('YYYY/MM/DD HH:mm:ss'), lastMsg }
        });
        item.list = newConvers;
      }
    });
    setListByGroup(groupList);
  }

  const handleCollectionOk = async (tagCodes, cid) => {
    try {
      await mySdkStore.sdk.collectSession({ cid, tagCodes });
      Toast.show('标记成功');
      setCollectCompProps({ visible: false });
    } catch(e) {
      console.log(e);
    }
  }

  const handleCollect = (cid) => {
    setCollectCompProps({
      visible: true,
      cid,
      onOk: (tagCode) => handleCollectionOk(tagCode, cid),
      onClose: () => setCollectCompProps({ visible: false }),
    });
  }

  const conversationEdit = (action, converInfo) => {
    const { lastMsgId, cid, bizParams = {} } = converInfo;
    console.log('conversationEdit>>>', action, converInfo);
    const { val } = action;
    if(!mySdkStore.sdk) return;
    if(val === 'allRead') {
      //消息游标已读
      mySdkStore.sdk.changeMessagesStatus({type: 'read', cursorMsgId: lastMsgId, cid});
      // setConverList((preConverList) => {
      //   const matchIndex = preConverList.findIndex(conver => conver.cid === cid);
      //   if(matchIndex > -1) {
      //     const matchItem = preConverList[matchIndex]
      //     preConverList[matchIndex] = {...matchItem, unReadCount: 0 };
      //   }
      //   return [...preConverList];
      // });
    }
    if(val === 'is_default_read') {
      //会话新消息默认已读
      const newDefaultReadState = !bizParams.is_default_read;
      mySdkStore.sdk.setConversationTag({ cid, type: 'is_default_read', value: newDefaultReadState });
      // setConverList((preConverList) => {
      //   const matchIndex = preConverList.findIndex(conver => conver.cid === cid);
      //   if(matchIndex > -1) {
      //     const matchItem = preConverList[matchIndex]
      //     const { bizParams = {} } = matchItem;
      //     preConverList[matchIndex] = {...matchItem, bizParams: { ...bizParams, is_default_read: newDefaultReadState } };
      //   }
      //   return [...preConverList];
      // });
    }
  }

  const handleRemoveConversation = async (cid, groupId) => {
    const res = await mySdkStore.sdk.addConversationUserMark({ cid, marks: [{ propertyName: 'is_hidden', propertyValue: 1 }] });
    if (res?.errorMessage) {
      Toast.show(res.errorMessage);
      return;
    }

    setListByGroup(listByGroup => listByGroup.map(item => {
      if (item.id === groupId) {
        const newList =  item.list.filter(item => item.cid !== cid);
        return { ...item, list: newList };
      }
        return item;
      })
    )
  }

  const handleToggleToTopGroup = async (rowData, groupId) => {
    const { cid, topMode } = rowData;
    if (!topMode) {
      // 置顶
      rowData.topMode = true;
      await mySdkStore.sdk.addConversationToGroups({ cid, groupId: topModeId });
      setListByGroup(listByGroup => listByGroup.map(item => {
          if (item.id === groupId) {
            const newList = item.list.filter(item => item.cid !== cid);
            return { ...item, list: newList };
          }
          if (item.id === topModeId) {
            const newList = [...item.list, rowData];
            return { ...item, list: newList };
          }
          return item;
        })
      );
    } else {
      // 取消置顶
      rowData.topMode = false;
      await mySdkStore.sdk.removeConversationFromGroups({ cid, groupId: topModeId });
      setListByGroup(listByGroup => listByGroup.map(item => {
          if (item.id === groupId) {
            const newList = item.list.filter(item => item.cid !== cid);
            return { ...item, list: newList };
          }

          if (rowData.shieldMode && item.groupName.includes('免打扰')) {
            const newList = [...item.list, rowData];
            return { ...item, list: newList };
          }

          if (!rowData.shieldMode && rowData.type === ConversationType.Single && item.groupName.includes('单聊')) {
            const newList = [...item.list, rowData];
            return { ...item, list: newList };
          }

          if (!rowData.shieldMode && rowData.type === ConversationType.Group && item.groupName.includes('群聊')) {
            const newList = [...item.list, rowData];
            return { ...item, list: newList };
          }
          return item;
        })
      );
    }
  }

  const renderRow = (rowData, groupId) => {
    const { cid, bizParams = {} } = rowData;
    const { is_default_read } = bizParams;
    const collectAction = {
      key: 'collect',
      text: '收藏',
      color: 'warning',
      onClick: () => handleCollect(cid),
    };
    const stayTopAction = {
      key: 'stayTop',
      text: !rowData.topMode ? '置顶' : '取消置顶',
      color: 'primary',
      onClick: (e) => { e.stopPropagation(); handleToggleToTopGroup(rowData, groupId) }
    };
    const deleteAction = {
      key: 'delete',
      text: '移除',
      color: 'danger',
      onClick: () => handleRemoveConversation(cid, groupId),
    };

    const rightActions = rowData.type === ConversationType.Notify ? [collectAction, stayTopAction] : [collectAction, stayTopAction, deleteAction];
    if (mySdkStore.isHideSomeFunctions) {
      rightActions.shift();
    }
    return (
      <SwipeAction
        rightActions={rightActions}
      >
        <ChatInboxCard
        key={cid}
        // onCardClicked={() => toChatPage(cid)}
        {...rowData}
        isDefaultRead={is_default_read}
        editFunc={(action) => conversationEdit(action, rowData)}
        />
      </SwipeAction>
    )
  };

  return <div className="converList">
    {listByGroup.map(item =>
      <List key={item.id} style={{ '--border-bottom': 0, '--border-inner': 0 }}>
        <List.Item style={{ padding: '12px' }} key="title" onClick={() => history.push({ pathname: `/conversationGroupList/${item.id}`})}>{item.groupName}</List.Item>
        { (item.list??[]).map(subItem =>
          <List.Item key={subItem.cid}>
            {renderRow(subItem, item.id)}
          </List.Item>)}
      </List>
    )}
  </div>
})

export default ConverList;